package com.raft.framework.db;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Build.VERSION;
import com.raft.framework.utils.AssetUtils;

import java.io.File;

public abstract class SimpleDBHelper extends SQLiteOpenHelper {
  protected SQLiteDatabase sqLiteDatabase;


  private Context context;
  private String dbName;

  public SimpleDBHelper(Context context,String name) {
    super(context,name,null,1);
    this.context = context;
    this.dbName = name;
  }
  protected abstract String getAssetFile();


  protected void init(){
    createDataBase();
    openDataBase();
  }

  @Override
  public void onCreate(SQLiteDatabase db) {

  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {


  }

  private String getDBPath(){
    return getDBFile().getPath();
  }


  private File getDBFile(){
    return context.getDatabasePath(dbName);
  }

  private void createDataBase() {
    if (!checkDataBase()) {
      if (VERSION.SDK_INT < 28){
        super.getReadableDatabase();
      }

      AssetUtils.copy(context,getAssetFile(),context.getDatabasePath(dbName));
    }
  }

  private boolean checkDataBase() {

    if(!getDBFile().exists()){
      return false;
    }

    SQLiteDatabase checkDB = null;
    try {
      checkDB = SQLiteDatabase.openDatabase(getDBPath(), null, SQLiteDatabase.OPEN_READONLY);
    } catch (SQLiteException e) {
      //database does't exist yet.
    }

    if (checkDB != null) {
      checkDB.close();
    }
    return checkDB != null;
  }



  private void openDataBase()throws SQLException {

    sqLiteDatabase = SQLiteDatabase.openDatabase(getDBPath(), null, SQLiteDatabase.OPEN_READONLY);

  }

  @Override
  public synchronized void close() {
    if (sqLiteDatabase != null){
      sqLiteDatabase.close();
    }
    super.close();
  }


  protected void closeCursor(Cursor cursor){
    if(cursor != null){
      cursor.close();
    }
  }

}
